package com.guchenbo.example.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class EchoInvocationHandler implements InvocationHandler {
    private EchoService target;

    public EchoInvocationHandler(EchoService target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("echo")) {
            System.out.println("before");
        }
        return method.invoke(target, args);
    }

    private static boolean isProxyOfSameInterfaces(Object arg, Class<?> proxyClass) {
        return proxyClass.isInstance(arg)
                        // Equal proxy instances should mostly be instance of proxyClass
                        // Under some edge cases (such as the proxy of JDK types serialized and then deserialized)
                        // the proxy type may not be the same.
                        // We first check isProxyClass() so that the common case of comparing with non-proxy objects
                        // is efficient.
                        || (Proxy.isProxyClass(arg.getClass())
                        && Arrays.equals(arg.getClass().getInterfaces(), proxyClass.getInterfaces()));
    }
}
